<template>
  <div>
    <tree-select
      class="typeSelect"
      :clearable="true"
      :searchable="true"
      :open-on-click="true"
      :placeholder="placeholder"
      :alwaysOpen="false"
      :options="options"
      v-model="typeId"
      :noOptionsText="noOptionsText"
      :noResultsText="noResultsText"
      :normalizer="normalizer"
      :style="{'--transform': transform}"
      :beforeClearAll="clearHandler"
      @open="reverseOpen"
      @close="reverseClose"
      @select="changeHandler"
    />
  </div>
</template>
<script>
import { getDocumentTypes } from '@src/api/Repository'
import { message } from '@src/util/message'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import i18n from '@src/locales'
export default {
  name: 'wiki-type-search',
  props: {
    value: {
      type: [String, Number],
      default: null,
    },
  },
  components: {
    TreeSelect,
  },
  computed: {
    placeholder() {
      return i18n.t('common.placeholder.inputSomething', {data1: i18n.t('wiki.create.textTitle.label2')})
    },
    noOptionsText() {
      return i18n.t('common.base.tip.noData')
    },
    noResultsText() {
      return i18n.t('common.base.tip.noData')
    },
  },
  data() {
    return {
      options: [], // 文章分类
      typeId: this.value, // 文章分类id
      transform: 'rotate(0deg)',
    }
  },
  created () {
    getDocumentTypes().then(res=>{
      if(res.success){
        this.options = res.result || []
        this.typeId = this.value || this.options[0]?.id
        this.$emit('update', this.typeId)
      }else{
        message.error(res.message)
      }
    });
  },
  methods: {
    reverseClose() {
      this.transform = 'rotate(0deg)'
    },
    reverseOpen() {
      this.transform = 'rotate(180deg)'
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.subTypes?.length ? node.subTypes : void 0
      }
    },
    changeHandler(value){
      this.$emit('update', value.id)
    },
    clearHandler() {
      // 清除的时候typeId不能为''，否则会显示unknown
      this.typeId = null
      this.$emit('update', null)
    }
  },
};
</script>